package service;

import com.example.friend.MainActivity;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import db.MyDatabase;
import db.ServiceDatabase;

public class SmsSendService extends Service {
	private class SmsObserver extends ContentObserver {

		private Context mContext;
		// private String smsBody = "";
		private String phone = "";
		// private long smsDatTime = System.currentTimeMillis();
		final Uri SMS_STATUS_URI = Uri.parse("content://sms");

		public SmsObserver(Handler handler, Context ctx) {
			super(handler);
			mContext = ctx;
		}

		public boolean deliverSelfNotifications() {
			return true;
		}

		public void onChange(boolean selfChange) {
			try {
				Cursor sms_sent_cursor = mContext.getContentResolver().query(SMS_STATUS_URI, null, null, null, null);
				if (sms_sent_cursor != null) {
					if (sms_sent_cursor.moveToFirst()) {
						String protocol = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("protocol"));
						if (protocol == null) {
							int type = sms_sent_cursor.getInt(sms_sent_cursor.getColumnIndex("type"));
							if (type == 2) {
								// smsBody =
								// sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("body")).trim();
								MyDatabase db = MainActivity.getDB();
								phone = ServiceDatabase.refinePhone(sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("address")).trim());
								db.updateSeen(phone, "sms");
								// smsDatTime =
								// sms_sent_cursor.getLong(sms_sent_cursor.getColumnIndex("date"));
							}
						}
					}
				} else {
				}
			} catch (Exception sggh) {
			}
			super.onChange(selfChange);
		}// fn onChange
	}// End of class SmsObserver

	SmsObserver smsObserver;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		final Uri SMS_STATUS_URI = Uri.parse("content://sms");
		smsObserver = new SmsObserver(new Handler(), this);
		this.getContentResolver().registerContentObserver(SMS_STATUS_URI, true, smsObserver);
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		this.getContentResolver().unregisterContentObserver(smsObserver);
		super.onDestroy();
	}
}
